//
//  CustomAddViewController.m
//  customer
//
//  Created by Holothurian on 2018/10/21.
//  Copyright © 2018年 yinlong. All rights reserved.
//

#import "CustomAddViewController.h"
#import "DecorateAppointMultiTableViewCell.h"
#import "CustomAdditionCaseListViewController.h"
#import "AppointmentCenterViewController.h"
#import "CouponListModel.h"

static NSString *DefaultIDentifier = @"DefaultIDentifier";
static NSString *TapSelectIDentifier = @"TapSelectIDentifier";
static NSString *Square2IDentifier = @"Square2IDentifier";
static NSString *InputTextIDentifier = @"InputTextIDentifier";
static NSString *PositionSelectIDentifier = @"PositionSelectIDentifier";

@interface CustomAddViewController ()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource,DecorateTapSelectTableCellDelegate>

@property(nonatomic,strong)CouponListModel *couponModel;

@property (nonatomic,strong)AdvertiseView *adV;

@property (nonatomic,strong)UIScrollView *scrollView;

@property (nonatomic,strong)NSMutableArray *keyArray;

@property (nonatomic,strong)NSMutableArray *valueArray;

@property (nonatomic,strong)NSMutableArray *placeArray;

@property (nonatomic,strong)DecorateLocationModel *locationModel;

@property (nonatomic,assign)BOOL backFlag;


@end

@implementation CustomAddViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createView];
}

- (void)backTapClick{
    if (self.backFlag) {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)createView{
    self.title = @"定制加配";
    [self.view addSubview:self.scrollView];
    if (!self.adV) {
        self.adV = [self bannerView];
    }
    [self.scrollView addSubview:self.adV];
    [self refreshBanner:self.adV];
    
    self.tableView.frame = CGRectMake(0, self.adV.viewBottom + 10, F_DEVICE_W, 450);
    self.tableView.bounces = NO;
    [self.tableView registerClass:[DecorateAppointDefaultTableCell class] forCellReuseIdentifier:DefaultIDentifier];
    [self.tableView registerClass:[DecorateAppointTapSelectTableCell class] forCellReuseIdentifier:TapSelectIDentifier];
    [self.tableView registerClass:[DecorateAppointSquare2TableCell class] forCellReuseIdentifier:Square2IDentifier];
    [self.tableView registerClass:[DecorateAppointInputTextTableCell class] forCellReuseIdentifier:InputTextIDentifier];
    [self.tableView registerClass:[DecorateAppointPositionSelectTableCell class] forCellReuseIdentifier:PositionSelectIDentifier];
    [self.scrollView addSubview:self.tableView];
    
    UIButton *appointButton = [UIButton buttonWithType:UIButtonTypeCustom];
    appointButton.frame = CGRectMake(30, F_DEVICE_H - NAVIGATION_BAR_HEIGHT - bottomPadding(20), F_DEVICE_W - 60, 50);
    appointButton.layer.cornerRadius = 6;
    appointButton.layer.masksToBounds = YES;
    [appointButton setBackgroundColor:[HSPublic colorWithHexString:@"333333"]];
    [appointButton setImage:[UIImage imageNamed:@"customAddImg"] forState:UIControlStateNormal];
    [appointButton setImage:[UIImage imageNamed:@"customAddImg"] forState:UIControlStateSelected];
    [appointButton setTitle:@"立即加配" forState:UIControlStateNormal];
    [appointButton setTitle:@"立即加配" forState:UIControlStateSelected];
    [appointButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [appointButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [appointButton addTarget:self action:@selector(appointmentAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:appointButton];
    
    [self.keyArray addObjectsFromArray:@[@"项目名称",@"户型选择",@"方案选择",@"方案报价",@"联系人",@"联系电话",@"所在地区",@"详细地址"]];
    [self.placeArray addObjectsFromArray:@[@"选择项目名称",@"选择户型",@"选择方案",@"方案报价",@"请输入联系人",@"请输入手机号码",@"点击选择地址",@"街道名称门牌号"]];
    [self.valueArray addObjectsFromArray:@[self.caseListModel.customized_name?:@"",self.houseTypeModel.huxing_name?:@"",self.caseTypeModel.programme_name?:@"",self.caseTypeModel.programme_price?:@"",@"",@"",@"",@""]];
    [self getTheCouponModelInfor];
}


- (AdvertiseView *)bannerView{
    return [[AdvertiseView alloc]initWithFrame:CGRectMake(0, 0, f_Ad_Content_W, f_Ad_Content_H)];
}

/**
 查看预约
 */
- (void)checkOutAppointment{
    AppointmentCenterViewController *orderDetail = [[AppointmentCenterViewController alloc]init];
    orderDetail.selectIndex = 2;
    TAB_PUSH(self, orderDetail, YES);
}


#pragma mark - - 根据场景获取优惠券
-(void)getTheCouponModelInfor{
    AutoWeakSelf
    
    if (k_Is_Empty(self.caseTypeModel.programme_price)) {
        return;
    }
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:0];
    [dict setObject:[NSString emptyStr:K_UserDefault_Read(CustomerUserAccount)] forKey:@"member_account"];
    [dict setObject:[NSNumber numberWithDouble:self.caseTypeModel.programme_price.doubleValue] forKey:@"fee"];
    [dict setObject:[NSNumber numberWithInt:5] forKey:@"use_scene"];
    
    
    [[QYNetManager sharedManager]POST:kGetCanUserCoupon parameters:dict andApiTyp:CustomerApiTypGetOrders SuccessBlock:^(id responseObject) {
        [weakSelf hideLoading];
        if ([responseObject[@"status"] isEqualToString:@"error"]) {
            [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
        }else if ([responseObject[@"status"] isEqualToString:@"pending"]|| [responseObject[@"data"] isKindOfClass:[NSNull class]]){
            [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
        }else if ([[NSString stringWithFormat:@"%@",responseObject[@"success"]] isEqualToString:@"1"]){
            NSDictionary *data = responseObject[@"data"];
            if (![data isKindOfClass:[NSNull class]] && [data isKindOfClass:[NSDictionary class]] && [data count]){
                weakSelf.couponModel = [CouponListModel yy_modelWithJSON:data];
                if (k_Is_Empty(weakSelf.couponModel.rule)) {
                }else{
                    //满减券
                    SLog(@"rule = %@ money = %@",weakSelf.couponModel.rule,weakSelf.couponModel.money);
                    if ([weakSelf.couponModel.rule isEqualToString:@"1"]) {
                        [weakSelf.valueArray replaceObjectAtIndex:3 withObject:[NSString stringWithFormat:@"%@",[NSNumber numberWithDouble:weakSelf.caseTypeModel.programme_price.doubleValue - weakSelf.couponModel.money.doubleValue]]];
                    }else{
                        //折扣券
                        [weakSelf.valueArray replaceObjectAtIndex:3 withObject:[NSString stringWithFormat:@"%@",[NSNumber numberWithDouble:weakSelf.caseTypeModel.programme_price.doubleValue - (weakSelf.couponModel.money.doubleValue)*weakSelf.caseTypeModel.programme_price.doubleValue]]];
                    }
                    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:3 inSection:0];
                    [weakSelf.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
                }
            }else{
                NSLog(@"暂无优惠券可用");
            }
        }else{
            [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
        }
    } Failure:^(NSError *error) {
        [weakSelf hideLoading];
        [weakSelf showErrorTipWithTitle:CustomerPoolNetStr];
    }];
}

- (void)appointmentAction:(UIButton *)sender{
    AutoWeakSelf
    
    if (k_Is_Empty(self.valueArray[4])) {
        [self showErrorTipWithTitle:@"请输入联系人姓名"];
        return;
    }
    if (k_Is_Empty(self.valueArray[5])&& [self.valueArray[5] length] != 11) {
        [self showErrorTipWithTitle:@"请输入正确的手机号码"];
        return;
    }
    if (k_Is_Empty(self.valueArray[6]) || !self.locationModel) {
        [self showErrorTipWithTitle:@"请选择地址"];
        return;
    }
    if (k_Is_Empty(self.valueArray[7])) {
        [self showErrorTipWithTitle:@"请填写街道名称门牌号"];
        return;
    }
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:0];
    [dict setObject:[NSString emptyStr:K_UserDefault_Read(CustomerUserID)] forKey:@"member_id"];
    [dict setObject:[NSString emptyStr:K_UserDefault_Read(CustomerUserToken)] forKey:@"member_token"];
    [dict setObject:self.caseListModel.customized_id forKey:@"customized_id"];
    [dict setObject:self.houseTypeModel.huxing_id forKey:@"huxing_id"];
    [dict setObject:self.caseTypeModel.programme_id forKey:@"programme_id"];
    [dict setObject:self.valueArray[4] forKey:@"contact_name"];
    [dict setObject:self.valueArray[5] forKey:@"contact_mobile"];
    [dict setObject:self.locationModel.province?:@"" forKey:@"address_provider"];//省
    [dict setObject:self.locationModel.city?:@"" forKey:@"address_city"];//市
    [dict setObject:self.locationModel.country?:@"" forKey:@"address_country"];//区
    [dict setObject:self.valueArray[7]?:@"" forKey:@"address_detail"];//详情地址
    
    [[QYNetManager sharedManager]POST:kInsertCustomizedOrder parameters:dict andApiTyp:CustomerApiTypGetOrders SuccessBlock:^(id responseObject) {
        [weakSelf hideLoading];
        if ([responseObject[@"status"] isEqualToString:@"error"]) {
            [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
        }
        else if ([responseObject[@"status"] isEqualToString:@"pending"]|| [responseObject[@"data"] isKindOfClass:[NSNull class]]){
            [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
        }else{
            NSInteger result = [responseObject[@"data"] integerValue];
            if (result) {
                //展示预约成功界面
                [weakSelf showSubmitSuccessPageWithTitle:@"定制加配预约成功" Somebody:@"客服联系" ButtonTitle:@""];
                weakSelf.backFlag = YES;
            }else{
                [weakSelf showErrorTipWithTitle:@"预约失败"];
            }
        }
    } Failure:^(NSError *error) {
        [weakSelf hideLoading];
        [weakSelf showErrorTipWithTitle:CustomerPoolNetStr];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.keyArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0 || indexPath.row == 1 || indexPath.row == 2 || indexPath.row == 3) {
        DecorateAppointTapSelectTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:TapSelectIDentifier];
        cell.delegate = self;
        cell.downImgView.hidden = YES;
        cell.nameLabel.text = self.keyArray[indexPath.row];
        cell.nameLabel.textColor = [HSPublic colorWithHexString:@"B2B2B2"];
        cell.selectTypeLabel.textColor = [HSPublic colorWithHexString:@"333333"];
        cell.selectTypeLabel.text = self.valueArray[indexPath.row];
        return cell;
    }else if (indexPath.row == 4 || indexPath.row == 5 || indexPath.row == 7){
        DecorateAppointInputTextTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:InputTextIDentifier];
        cell.indexPath = indexPath;
        cell.delegate = self;
        cell.nameLabel.text = self.keyArray[indexPath.row];
        cell.textField.placeholder = self.placeArray[indexPath.row];
        [cell.textField setValue:[HSPublic colorWithHexString:@"B2B2B2"] forKeyPath:@"_placeholderLabel.textColor"];
        cell.textField.text = self.valueArray[indexPath.row];
        if (indexPath.row == 5) {
            cell.textField.keyboardType = UIKeyboardTypeNumberPad;
        }else{
            cell.textField.keyboardType = UIKeyboardTypeDefault;
        }
        return cell;
    }else if (indexPath.row == 6){
        DecorateAppointPositionSelectTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:PositionSelectIDentifier];
        cell.nameLabel.text = self.keyArray[indexPath.row];
        [cell cellForLayout:self.valueArray[indexPath.row]];
        cell.delegate = self;
        return cell;
    }else{
        DecorateAppointDefaultTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:DefaultIDentifier];
        cell.nameLabel.text = self.keyArray[indexPath.row];
        cell.detailNameLabel.text = self.valueArray[indexPath.row];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50.f;
}

#pragma mark - DecorateTapSelectTableCellDelegate
/**
 类型选择
 */
- (void)tapSelectTableCellEventWithIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"点击选择类型");
    CustomAdditionCaseListViewController *addition = [[CustomAdditionCaseListViewController alloc]init];
    TAB_PUSH(self, addition, YES);
}

/**
 地址选择
 */
- (void)tapPlaceTableCellEvent{
    [self.view endEditing:YES];
    BaseLocationManagerVC *location = [[BaseLocationManagerVC alloc]init];
    AutoWeakSelf
    location.locationBlock = ^(DecorateLocationModel *locationModel) {
        weakSelf.locationModel = locationModel;
        [weakSelf.valueArray replaceObjectAtIndex:6 withObject:weakSelf.locationModel.prefixArea];
        [weakSelf.valueArray replaceObjectAtIndex:7 withObject:weakSelf.locationModel.suffixArea];
        [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:6 inSection:0],[NSIndexPath indexPathForRow:7 inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
    };
    TAB_PUSH(self, location, YES);
}

- (void)modifSingleTextFieldTableCell:(NSIndexPath *)indexPath WithEditEndText:(NSString *)text{
    if (k_Is_Empty(text)) {
        return;
    }
    [self.valueArray replaceObjectAtIndex:indexPath.row withObject:text];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}


#pragma mark - GETTER
- (UIScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0,NAVIGATION_BAR_HEIGHT, F_DEVICE_W, F_DEVICE_H - NAVIGATION_BAR_HEIGHT - bottomPadding(0))];
        _scrollView.delegate = self;
        _scrollView.contentSize = CGSizeMake(F_DEVICE_W,f_Ad_Content_H + 550);
    }
    return _scrollView;
}

- (NSMutableArray *)keyArray{
    if (!_keyArray) {
        _keyArray = [NSMutableArray array];
    }
    return _keyArray;
}

- (NSMutableArray *)valueArray{
    if (!_valueArray) {
        _valueArray = [NSMutableArray array];
    }
    return _valueArray;
}

- (NSMutableArray *)placeArray{
    if (!_placeArray) {
        _placeArray = [NSMutableArray array];
    }
    return _placeArray;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
